<?php

namespace app\controller;


use app\BaseController;
use app\exceptions\CustomException;
use app\Request;
use app\Result;
use app\validate\inLogValidate;
use DateTime;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class InLog extends BaseController
{

    /**
     * @param Request $request
     * @return Json
     * @throws ValidateException
     * @throws DbException
     */
    public function addInLog(Request $request): Json
    {

        $time = new DateTime();
        $data = [
            "commodity_id" => $request->post("commodity_id"),
            "dealer" => $request->post("dealer"),
            "in_num" => $request->post("in_num"),
            "in_price" => $request->post("in_price"),
            "payment" => $request->post("payment"),
            "time" => $time->format("Y-m-d H:i:s")
        ];

        validate(inLogValidate::class)->check($data);

        Db::name("in_log")->save(
            $data
        );

        Db::name("commodity")->where("commodity_id", $data['commodity_id'])->inc("num", $data["in_num"])->update();
        return Result::success(null, "入库成功！");

    }

    /**
     * @throws DbException
     */
    public function getList(Request $request): Json
    {
        $commodity_id = $request->post("commodity_id");
        $pageSize = $request->post("pageSize");
        $pageNo = $request->post("pageNo");

        if (!$commodity_id) {
            throw new CustomException(10001, "请输入商品ID");
        }
        $data = Db::name("in_log")->where("commodity_id", $commodity_id)->paginate([
            'list_rows' => $pageSize,
            'page' => $pageNo,
        ]);
        return Result::success($data);
    }
}